package pl.edu.pk.rz.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import pl.edu.pk.rz.command.LoginCommand;
import pl.edu.pk.rz.entity.User;
import pl.edu.pk.rz.exception.UserNotFoundException;
import pl.edu.pk.rz.validator.UserValidator;

@Controller
public class LoginController extends AbstractController {

	@Autowired
	private UserValidator userValidator;
	
	@ModelAttribute(COMMAND)
	public LoginCommand stworzLogowanieCommand() {
		return new LoginCommand();
	}

	@RequestMapping(value = URL_LOGIN, method = RequestMethod.GET)
	public ModelAndView showLoginForm(HttpSession session) {
		if(session.getAttribute(SESSION_PARAM_USER) != null){
			return new ModelAndView("redirect:/show-page");
		}
		logger.info("Request for login page");
		Map<String, Object> model = new HashMap<String, Object>();
		feedPagesList(model);
		return new ModelAndView(VIEW_LOGIN, MODEL, model);
	}

	@RequestMapping(value = URL_LOGIN, method = RequestMethod.POST)
	public ModelAndView login(@ModelAttribute(COMMAND) LoginCommand command, HttpSession session, BindingResult bindingResult, HttpServletRequest request) {
		logger.info("Logging user "+command.getUsername());
		userValidator.validate(command, bindingResult);
		Map<String, Object> model = new HashMap<String, Object>();
		feedPagesList(model);
		model.put(COMMAND, command);
		try {
			User user = userService.login(command.getUsername(), command.getPassword());
			session.setAttribute(SESSION_PARAM_USER, user);
			// session.setAttribute(INFORMACJA, LOGOWANIE_POWODZENIE);
			return new ModelAndView("redirect:/show-page");
		} catch (UserNotFoundException e) {
			// session.setAttribute(INFORMACJA, LOGOWANIE_NIEPOWODZENIE);
			logger.info("User " + command.getUsername() + " not found");
			return new ModelAndView(VIEW_LOGIN, MODEL, model);
		}

	}

	@RequestMapping(value = URL_LOGOUT)
	public ModelAndView wyloguj(HttpSession session) {
		session.setAttribute(SESSION_PARAM_USER, null);
		// session.setAttribute(INFORMACJA, LOGOWANIE_WYLOGOWANO);
		return new ModelAndView("redirect:/show-page");
	}
}
